package meb

import (
	"errors"
	"github.com/gin-gonic/gin"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// ProductBuyQry 产品购买结构查询，用于前端查支付结果
func (ctl *Controller) ProductBuyQry(ctx *gin.Context) (err error) {
	var (
		uid    = hgin.CtxToken(ctx).Uid
		args   = hgin.ApiReq[ProductBuyQryArgs](ctx)
		prodId = args.ProdId
	)
	if prodId == "" {
		err = errors.New("产品编号不能为空")
		return
	}

	// 用户+产品取订单号
	var orderId string
	if orderIdAny := ctl.cache.Get(uid + prodId); orderIdAny != nil {
		orderId = orderIdAny.(string)
	}
	if orderId == "" {
		err = errors.New("没有查到订单")
		return
	}

	var order model.Order
	if err = ctl.db.Where("order_id = ?", orderId).Take(&order).Error; err != nil {
		return
	}

	// 待支付订单查询状态
	if order.Status == model.ORDER_UNPAID {
		err = wxpayQuery(ctl, order.OrderId)
		if err != nil {
			return
		}
		// 支付成功,修改订单状态，执行发货
		order.Status = model.ORDER_PAYSUC
	}

	//已支付订单执行发货
	if order.Status == model.ORDER_PAYSUC {
		order, err = ctl.OrderService.FinishVip(order.OrderId)
		if err != nil {
			return
		}
	}

	hgin.ApiRes(ctx, OrderWxpayQueryBody{
		OrderId: order.OrderId,
		Status:  order.Status,
	})
	return
}

type ProductBuyQryArgs struct {
	ProdId string `json:"prod_id"`
}

type ProductBuyQryBody struct {
	OrderId string            `json:"order_id"`
	Status  model.OrderStatus `json:"status"`
}
